<template>
  <div class="editor-container">
    <div ref="editable" @click="handleClick" @keydown="handleKeydown">
      <!-- 使用v-for渲染所有内容块 -->
      <component 
        v-for="(block, index) in editorBlocks" 
        :key="index"
        :is="block.type === 'text' ? 'span' : 'non-editable-tag'"
        v-html="block.content"
        @insert="insertAt(index)"
      ></component>
    </div>
    
    <button @click="insertText">在光标处插入“备注值”</button>
    <div v-if="feedbackMessage" class="feedback">{{ feedbackMessage }}</div>
  </div>
</template>

<script>
import NonEditableTag from './nonEditableTag.vue'
export default {
  name: 'TextEditor',
  components: {
    NonEditableTag
  },
  data() {
    return {
      editorBlocks: [
        { type: 'tag', content: '【分行名称】' },
        { type: 'text', content: '' },
        { type: 'tag', content: '【性别】' }
      ],
      selectedIndex: -1,
      feedbackMessage: '',
      feedbackTimer: null
    }
  },
  methods: {
    handleClick(e) {
      // 检查点击是否在文本区域
      const target = e.target;
      if (target === this.$refs.editable || target.tagName === 'DIV') {
        this.selectedIndex = 1; // 默认选择第一个文本区域
        return;
      }
      
      // 找到点击的组件索引
      const blocks = this.$refs.editable.children;
      for (let i = 0; i < blocks.length; i++) {
        if (blocks[i].contains(target)) {
          // 如果点击的是不可编辑标签，选择其下一个文本区域
          if (blocks[i].getAttribute('contenteditable') === 'false') {
            this.selectedIndex = i + 1;
          } else {
            this.selectedIndex = i;
          }
          break;
        }
      }
    },
    
    handleKeydown(e) {
      // 确保只在选中的文本区域处理输入
      if (this.selectedIndex < 0 || this.selectedIndex >= this.editorBlocks.length) {
        e.preventDefault();
        return;
      }
      
      const block = this.editorBlocks[this.selectedIndex];
      if (block.type !== 'text') {
        e.preventDefault();
        return;
      }
      
      // 处理特殊按键（如Enter、Backspace等）
      if (e.key === 'Enter') {
        e.preventDefault();
        this.splitBlockAtCursor();
      }
    },
    
    insertText() {
      if (this.selectedIndex < 0 || this.selectedIndex >= this.editorBlocks.length) {
        this.showFeedback('请先选择可编辑区域');
        return;
      }
      
      const block = this.editorBlocks[this.selectedIndex];
      if (block.type !== 'text') {
        this.showFeedback('请在可编辑区域插入内容');
        return;
      }
      
      // 更新文本内容
      this.$set(this.editorBlocks, this.selectedIndex, {
        type: 'text',
        content: block.content + '备注值'
      });
      
      this.hideFeedback();
    },
    
    insertAt(index) {
      this.selectedIndex = index;
      this.insertText();
    },
    
    splitBlockAtCursor() {
      // 这里需要使用Selection API获取光标位置
      // 然后分割当前文本块
      // 简化实现，实际项目中可能需要更复杂的逻辑
      const selection = window.getSelection();
      if (!selection || selection.rangeCount === 0) return;
      
      const range = selection.getRangeAt(0);
      const selectedBlock = this.editorBlocks[this.selectedIndex];
      
      // 获取光标在文本中的位置
      const textNode = range.startContainer;
      const offset = range.startOffset;
      
      if (textNode.nodeType === Node.TEXT_NODE && textNode.parentElement === this.$refs.editable.children[this.selectedIndex]) {
        const text = textNode.textContent;
        const beforeText = text.substring(0, offset);
        const afterText = text.substring(offset);
        
        // 更新当前块
        this.$set(this.editorBlocks, this.selectedIndex, {
          type: 'text',
          content: beforeText
        });
        
        // 插入新块
        this.editorBlocks.splice(this.selectedIndex + 1, 0, 
          { type: 'text', content: afterText }
        );
        
        // 更新选中索引
        this.selectedIndex++;
      }
    },
    
    showFeedback(message) {
      this.feedbackMessage = message;
      
      if (this.feedbackTimer) {
        clearTimeout(this.feedbackTimer);
      }
      
      this.feedbackTimer = setTimeout(() => {
        this.hideFeedback();
      }, 3000);
    },
    
    hideFeedback() {
      this.feedbackMessage = '';
      if (this.feedbackTimer) {
        clearTimeout(this.feedbackTimer);
        this.feedbackTimer = null;
      }
    }
  },
  beforeDestroy() {
    if (this.feedbackTimer) {
      clearTimeout(this.feedbackTimer);
    }
  }
}
</script>

<style scoped>
.editor-container {
  margin: 20px;
}

[contenteditable=false] {
  border: 1px solid blue;
  padding: 2px 4px;
  margin: 0 2px;
  background: #f9f9f9;
  user-select: none;
  cursor: default;
}

#editable {
  border: 1px solid #ccc;
  min-height: 100px;
  padding: 10px;
  margin-bottom: 10px;
}

.feedback {
  color: red;
  margin-top: 5px;
  min-height: 20px;
}
</style>
    